import random
from typing import List, Dict, Optional
from game_data import GameData


class Core:
    """游戏核心类，负责牌组管理和发牌逻辑"""

    def __init__(self, game_data: GameData):
        self.game_data = game_data
        self.target_card: Optional[str] = None
        self._initialize_deck()

    def _initialize_deck(self) -> None:
        """初始化牌组：6张Q，6张K，6张A，2张Joker"""
        self.deck = ['Q'] * 6 + ['K'] * 6 + ['A'] * 6 + ['Joker'] * 2
        random.shuffle(self.deck)

    def deal_cards(self) -> None:
        """给所有玩家发牌（每人5张）并随机选择目标牌"""
        # 确保所有玩家都有hand属性
        for player in self.game_data.character_data_game:
            if 'hand' not in player:
                player['hand'] = []
            else:
                player['hand'].clear()

        # 发牌
        for _ in range(5):
            for player in self.game_data.character_data_game:
                if self.deck:
                    player['hand'].append(self.deck.pop())

        # 随机选择目标牌
        self.target_card = random.choice(['Q', 'K', 'A'])
        print(f"目标牌已选择: {self.target_card}")

    def reset_round(self) -> None:
        """重置当前回合（重新洗牌和发牌）"""
        self._initialize_deck()
        self.deal_cards()

    def print_game_status(self) -> None:
        """打印当前游戏状态（简洁版，只打印一次）"""
        print("\n========= 游戏状态 =========")
        print(f"目标牌: {self.target_card}")
        print("玩家信息:")

        for player in self.game_data.character_data_game:
            print(f"{player['name']} ({player['model']}):")
            print(f"  手牌: {', '.join(player.get('hand', []))}")
            print(f"  子弹位置: {player.get('bullet_position_game', 'N/A')}")
            print(f"  当前位置: {player.get('current_position', 'N/A')}")
            print("-" * 30)

        print("=" * 40)